package com.yifeng.repo.base.utils.file;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * Created by daibing on 2020/4/9.
 */
public class WorkDirHelper {

    public static String getWorkDir(String remove) {
        String currentDir = getCurrentDir();
        String placeHolder = File.separator + remove;
        if (currentDir.endsWith(placeHolder)) {
            return currentDir.substring(0, currentDir.length() - placeHolder.length());
        } else {
            return currentDir;
        }
    }

    public static String getCurrentDir() {
        File file = new File(WorkDirHelper.class.getProtectionDomain().getCodeSource().getLocation().getFile());
        try {
            return URLDecoder.decode(file.getParent(), StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getCurrentFile() {
        String file = WorkDirHelper.class.getProtectionDomain().getCodeSource().getLocation().getFile();
        try {
            return URLDecoder.decode(file, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String currentDir = WorkDirHelper.getCurrentFile();
        System.out.println(currentDir);
    }

}
